#include "precomp.h"
#include "Game.h"

Game::Game(const char* map_file, CL_DisplayWindow *window)
	: _window(window)
{
	_gc = &(window->get_gc());
	_ic = &(window->get_ic());

	_map = new Map(map_file, WALL_DIR, _gc, 32);

	_player = new Player(CH_BLUE_DIR, _gc, _ic, _map, MAP_PLAYER);
	_ai = new AI(CH_RED_DIR, _gc, _map, MAP_AI, _player);

	_hud = new HUD(_player, _gc, CL_Pointf(0, WINDOW_HEIGHT - 60));

	_player->collide_character(_ai);
	_ai->collide_character(_player);
}

Game::~Game(){
	delete _map, _player, _ai, _hud;
}

void Game::win(){
	_draw_end_text(CL_String("YOU WIN\n(PRESS ESC TO CONTINUE)"));
	_hold();
}

void Game::lose(){
	_draw_end_text(CL_String("YOU LOSE\n(PRESS ESC TO CONTINUE)"));
	_hold();
}

int Game::start(){
	int last_time = CL_System::get_time(),
		current_time,
		delta_time;

	while (_ic->get_keyboard().get_keycode(CL_KEY_ESCAPE) == false){
		_gc->clear(CL_Colorf(CL_Colord::white));

		current_time = CL_System::get_time();
		delta_time = current_time - last_time;

		_player->tick(delta_time);
		_player->draw();

		_ai->tick(delta_time);
		_ai->draw();

		_map->draw(_player->get_x(), _player->get_y());

		_hud->tick(delta_time);
		_hud->draw();

		if(_ai->is_dead()){
			return GAME_WIN;
		}

		if(_player->is_dead()){
			return GAME_LOSE;
		}
		
		_window->flip();
		CL_KeepAlive::process();
		CL_System::sleep(10);

		last_time = current_time;
	}

	return GAME_CANCELED;
}

void Game::_hold(){
	while(_ic->get_keyboard().get_keycode(CL_KEY_ESCAPE) == false){	
		CL_KeepAlive::process();
		CL_System::sleep(10);
	}
}

void Game::_draw_end_text(CL_String text, int font_size, const wchar_t* font_type, CL_Color color){
	CL_Font win(*_gc, font_type, font_size);

	win.draw_text(*_gc, 20, GameObject::center_y - (font_size>>1), text, CL_Colorf(color));

	_window->flip();
}